//DemoFilter.java
package com.ylaihui;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author lisimmy www.ylaihui.com
 * @create 2021-08-04
 */
public class DemoFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        Object user = httpServletRequest.getSession().getAttribute("user");

        if(user == null) {
            //not login 如果用户未登录，那么拦截， 并转发到登录页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        } else {
            // 如果用户登录了，继续执行后面的逻辑
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
